package cn.mengfly.testnrz.im.client;

import lombok.Data;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Data
public class FutureTaskSchedule extends Thread {

    /**
     * 任务队列
     */
    private ConcurrentLinkedQueue<ExecuteTask> executeTasks = new ConcurrentLinkedQueue<>();

    /**
     * 线程休眠时间
     */
    private long sleepTime = 200;

    private ExecutorService pool = Executors.newFixedThreadPool(10);
    private static FutureTaskSchedule instance = new FutureTaskSchedule();

    private FutureTaskSchedule() {
        this.start();
    }

    @Override
    public void run() {
        while (true) {
            handleTask();
            threadSleep(sleepTime);
        }
    }

    public static void add(ExecuteTask task) {
        instance.executeTasks.add(task);
    }

    private void threadSleep(long time) {
        try {
            sleep(time);
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }
    }

    private void handleTask() {
        ExecuteTask executeTask;
        try {
            while (executeTasks.peek() != null) {
                executeTask = executeTasks.poll();
                handleTask(executeTask);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 执行异步任务
     *
     * @param task 任务
     */
    private void handleTask(ExecuteTask task) {
        pool.execute(new ExecuteRunnable(task));
    }

    class ExecuteRunnable implements Runnable {
        ExecuteTask executeTask;

        ExecuteRunnable(ExecuteTask task) {
            this.executeTask = task;
        }

        @Override
        public void run() {
            executeTask.execute();
        }
    }

}
